package com.example.composedemo

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.view.WindowCompat

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        WindowCompat.setDecorFitsSystemWindows(window, false)
        //设置状态栏字体颜色为反色（暗夜时为白色；白天时为黑色）
        val controller = WindowCompat.getInsetsController(window, window.decorView)
        controller.isAppearanceLightStatusBars = !isDarkMode()
        //状态栏背景色设置为透明
        window.statusBarColor = Color.Transparent.toArgb()

        val mainViewModel by viewModels<MainViewModel>()
        setContent {    // 设置显示内容，相当于 setContentView
            //主题切换 Demo
            ThemeDemoPage(mainViewModel)
        }
    }
}

@Preview
@Composable
fun PreViewContainer() {
    Greeting(name = "这里是 Greeting")
}

@Composable
fun Greeting(name: String) {
    val greetingTypography = MaterialTheme.typography
    val greetingColors = MaterialTheme.colors
    val customStyle = MaterialTheme.typography.h5.copy(color = Color.Green)
    Column() {
        Text(
            text = "Hello $name",
//        color = greetingColors.onBackground,
            style = customStyle
        )
        CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.disabled) {
            Text(
                text = "Hello, 修之竹~",
                style = MaterialTheme.typography.body1.copy(
                    letterSpacing = 5.sp
                ),
                fontSize = 20.sp
//                style = MaterialTheme.typography.body1
            )
        }
        val annotatedString = buildAnnotatedString {
            withStyle(SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
                append("Kotlin ")
            }
            append("是世上 ")
            withStyle(SpanStyle(fontSize = 24.sp)) {
                append("最好的语言")
            }
        }
        Text(text = annotatedString)
        Button(shape = MaterialTheme.shapes.small, onClick = {}) {
            Text(text = "small shape")
        }
        RoundedCornerImage(painter = painterResource(id = R.drawable.header), cornerSize = 90)
    }
}


@Composable
fun RoundedCornerImage(painter: Painter, cornerSize: Int) {
    Surface(
        shape = RoundedCornerShape(cornerSize.dp)
    ) {
        Image(
            painter = painter,
            contentDescription = "圆角图片"
        )
    }
}


//@Preview
//@Composable
//fun WrapperView() {
//    Greeting("hahahaha")
//}

//@Preview(showBackground = true)
//@Composable
//fun DefaultPreview() {
//    ComposeDemoTheme {
//        Greeting("Android")
//    }
//}

//@Preview
//@Composable
//fun NewStory() {
//    CustomTheme(isSystemInDarkTheme()) {
//        // 在 MaterialTheme 下就可以使用主题自带的文本段落样式了
//        val typography = MaterialTheme.typography
//        Column(
//            modifier = Modifier.padding(16.dp)
//        ) {
//            Image(
//                painter = painterResource(id = R.drawable.header),
//                contentDescription = null,
//                modifier = Modifier
//                    .height(180.dp)  // 高度设置为固定值 180dp
//                    .fillMaxWidth()  // 宽度填充所属布局
//                    .clip(shape = RoundedCornerShape(10.dp)), // 使用 clip 可设置 Shape，这里是圆角Shape
//                contentScale = ContentScale.Crop // 拉伸方式为 居中裁剪
//            )
//
//            Spacer(modifier = Modifier.height(16.dp)) // Spacer 提供留白
//
//            Text("今天天气好，适合出去玩耍。" +
//                    "蓝蓝的天空，白白的云，远处" +
//                    "还有小山头，绿绿的草坪",
//                style = typography.h6,
//                maxLines = 2,  // 最多展示两行
//                overflow = TextOverflow.Ellipsis)  // 超出行数则截断，用省略号省略
//            Text(text = "武汉",style = typography.body1, modifier = Modifier.padding(10.dp))
//            Surface (color = Color.Yellow,contentColor = Color.Red) {
//                Text(text = "July 2021",style = typography.body2)
//            }
////            ListWithBug(listOf("王二","张三","李四","二狗","二蛋"))
//
//            MyApp {
//                Text(text = "被容器函数所修饰的 Text")
//            }
//
//            Divider(color = Color.Cyan, thickness = 10.dp)    // 水平分割线
//
//            Counter()
//
////            MyScreenContent()
//
//            NameList(names = List<String>(100) {"Hello Android $it"})
//        }
//    }
//}


@Composable
@Deprecated("Example with bug")
fun ListWithBug(myList: List<String>) {
    var items = 0

    Row(horizontalArrangement = Arrangement.SpaceBetween) {
        Column {
            for (item in myList) {
                Text(text = "Item num = $items, Item = $item")
                items++  // Avoid! Side-effect of the column recomposing.
            }
        }
        Text(text = "Count: $items")
    }
}

// 声明一个容器函数
@Composable
fun MyApp(content: @Composable () -> Unit) {
    // 基础设置，类似于 Theme 等
    MaterialTheme() {
        Surface(color = Color.Yellow, modifier = Modifier.padding(10.dp)) {
            content()
        }
    }
}

// mutableStateOf remember 的用法
@Composable
fun Counter() {
    val count = remember { mutableStateOf(0) }
    Button(onClick = { count.value++ }) {
        Text(text = "已点击了 ${count.value} 次！")
    }
}

@Composable
fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
    Column(modifier = Modifier.fillMaxHeight()) {
        Column(modifier = Modifier.weight(1f)) {
            for (name in names) {
                Text(text = name)
                Divider(color = Color.Black)
            }
        }
        Button(onClick = { }) {
            Text(text = "这是第二个 Button")
        }
    }
}

@Composable
fun NameList(names: List<String>, modifier: Modifier = Modifier) {
    LazyColumn(modifier = modifier) {
        items(items = names) { name ->
            Greeting2(name = name)
            Divider(color = Color.Black)
        }
    }
}

@Composable
fun Greeting2(name: String) {
    var isSelected by remember {
        mutableStateOf(false)
    }
    val backgroundColor by animateColorAsState(if (isSelected) Color.Cyan else Color.Transparent)

    Text(
        text = "Hello $name!",
        modifier = Modifier
            .padding(10.dp)
            .background(color = backgroundColor)
            .clickable { isSelected = !isSelected })
}